#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2022
@author: GLTS
"""
import os
import sys
import json
import socket
import random
import requests
import datetime
import Weather_Dict
import tkinter as tk
import tkinter.messagebox

wek = datetime.datetime.today().weekday() + 1
wek1 = wek + 1
wek2 = wek + 2
if wek1 >= 8:
    wek1 -= 7
    wek2 -= 7
if wek2 >= 8:
    wek2 -= 7

week1 = Weather_Dict.week_list[wek1 - 1]
week2 = Weather_Dict.week_list[wek2 - 1]


# wifiConnectionStatus():


def setting():
    root = tk.Tk()
    root.title(title_name)
    root.geometry('428x200')
    root.geometry('+516+343')
    root.resizable(False, False)

    root.mainloop()


def about():
    pass


def forhelp():
    pass


def wcs(web='www.baidu.com', timeout=3):
    st = socket.socket()
    st.settimeout(timeout)
    try:
        status = st.connect_ex((web, 443))
        if status == 0:
            st.close()
            return True
        else:
            return False
    except Exception:
        return False


def find():
    if entry.get() == '':
        return 'Error_ValueNone'
    else:
        value = os.path.exists("weather.key")
        if value:
            key_file = open("weather.key", "r", encoding="utf-8")
            weather_key_list = key_file.readlines()
            list_temp = []
            for i in weather_key_list:
                list_temp.append(i.strip('\n')[23:])
            weather_key_list = list_temp

            api = "https://api.seniverse.com/v3/weather/"
            filename = "daily.json"
            weather_key = random.choice(weather_key_list)
            # uid = None
            city = entry.get()
            language = 'zh-Hans'
            unit = Weather_Dict.unit_list[0]

            url = api + filename + "?key=" + weather_key + "&location=" + city + "&language=" + language + \
                  "&unit=" + unit

            # print(url)

            """
            def fetchWeather(url_temp):
                result_temp = requests.get(url_temp, timeout=1)
                return result_temp.text

            result = fetchWeather(url)
            """
            result = requests.get(url, timeout=1).text
            # print(result)

            weather = json.loads(result)
            json_dict = json.dumps(weather, indent=2, ensure_ascii=False)
            # print(json_dict)
            # 解析 JSON 数据
            data = json.loads(json_dict)
            return data
        elif not value:
            tk.messagebox.showerror('错误', '重要文件"Weather.key"丢失，无法继续运行程序')
            sys.exit()


"""
def find():
    if entry.get() == '':
        tk.messagebox.showerror('错误', '未输入城市')
        return 'Error_ValueNone'
    else:
        weather_key_list = ['SsxyKoD5n-LXLJTYv',
                            'SUO_J2PG63xkGOFPQ',
                            'S38Lf8Uh8bh-UtYHz'
                            ]

        api = "https://api.seniverse.com/v3/weather/"
        filename = "daily.json"
        weather_key = random.choice(weather_key_list)
        # uid = None
        city = entry.get()
        language = 'zh-Hans'
        unit = 'c'

        url = api + filename + "?key=" + weather_key + "&location=" + city + "&language=" + language + "&unit=" + unit

        # print(url)

        def fetchWeather(url_temp):
            result_temp = requests.get(url_temp, timeout=1)
            return result_temp.text

        result = fetchWeather(url)
        # print(result)

        weather = json.loads(result)
        json_dict = json.dumps(weather, indent=2, ensure_ascii=False)
        # print(json_dict)
        # 解析 JSON 数据
        data = json.loads(json_dict)
        return data
"""


def find_error(data_temp):
    error_code = data_temp['status_code']
    if error_code in Weather_Dict.error_dict:
        tk.messagebox.showerror('错误', Weather_Dict.error_dict[error_code][1] + '\n' + '错误代码:' + error_code)
    else:
        tk.messagebox.showerror('错误', '未知错误')


# noinspection PyTypeChecker
def get_weather_two():
    api_wcs2 = wcs('api.seniverse.com', 3)
    if api_wcs2:
        data = find()
        if data == 'Error_ValueNone':
            tk.messagebox.showerror('错误', '未输入城市')
        elif not data == 'Error_ValueNone':
            try:
                data['status']
            except KeyError:
                # T
                root = tk.Tk()
                # root = tk.Toplevel()
                root.title(title_name)
                root.geometry('428x200')
                root.geometry('+516+343')
                root.resizable(False, False)

                # 天气框子1
                labelframe1 = tk.LabelFrame(root, width=185, height=175, text="周" + str(week1) + "天气", font=('', 11))
                labelframe1.grid(column=0, row=0, padx=15, pady=10)
                # 天气内容1
                text1 = tk.Text(root, font=('', 13))
                text1.place(x=32, y=42, width=150, height=120)
                # 天气框子2
                labelframe2 = tk.LabelFrame(root, width=185, height=175, text="周" + str(week2) + "天气", font=('', 11))
                labelframe2.grid(column=1, row=0, padx=15, pady=10)
                # 天气内容2
                text2 = tk.Text(root, font=('', 13))
                text2.place(x=247, y=42, width=150, height=120)

                # 访问数据
                # location_id = data['results'][0]['location']['id']
                # city_name = data['results'][0]['location']['name']

                today_date1 = data['results'][0]['daily'][1]['date']
                text_day1 = data['results'][0]['daily'][1]['text_day']
                text_night1 = data['results'][0]['daily'][1]['text_night']
                high_temp1 = data['results'][0]['daily'][1]['high']
                low_temp1 = data['results'][0]['daily'][1]['low']
                wind_direction1 = data['results'][0]['daily'][1]['wind_direction']
                wind_speed1 = data['results'][0]['daily'][1]['wind_speed']

                # code_day = data['results'][0]['daily'][0]['code_day']
                # code_night = data['results'][0]['daily'][0]['code_night']
                # rainfall = data['results'][0]['daily'][0]['rainfall']
                # precip = data['results'][0]['daily'][0]['precip']
                # humidity = data['results'][0]['daily'][0]['humidity']

                today_date2 = data['results'][0]['daily'][2]['date']
                text_day2 = data['results'][0]['daily'][2]['text_day']
                text_night2 = data['results'][0]['daily'][2]['text_night']
                high_temp2 = data['results'][0]['daily'][2]['high']
                low_temp2 = data['results'][0]['daily'][2]['low']
                wind_direction2 = data['results'][0]['daily'][2]['wind_direction']
                wind_speed2 = data['results'][0]['daily'][2]['wind_speed']

                text1.configure(state='normal')
                text1.insert('end', '日期:' + today_date1 + '\n')
                text1.insert('end', '天气:' + text_day1 + '-' + text_night1 + '\n')
                text1.insert('end', '最高温:' + high_temp1 + '\n')
                text1.insert('end', '最低温:' + low_temp1 + '\n')
                text1.insert('end', '风向:' + wind_direction1 + '\n')
                text1.insert('end', '风速:' + wind_speed1)
                text1.configure(state='disabled')

                text2.configure(state='normal')
                text2.insert('end', '日期:' + today_date2 + '\n')
                text2.insert('end', '天气:' + text_day2 + '-' + text_night2 + '\n')
                text2.insert('end', '最高温:' + high_temp2 + '\n')
                text2.insert('end', '最低温:' + low_temp2 + '\n')
                text2.insert('end', '风向:' + wind_direction2 + '\n')
                text2.insert('end', '风速:' + wind_speed2)
                text2.configure(state='disabled')

                root.mainloop()
            else:
                # F
                # tk.messagebox.showerror('错误', '你输入的城市名有误，或者天气中心未收录你所在城市')
                find_error(data)
    elif not api_wcs2:
        tk.messagebox.showerror('错误', '无法访问天气API服务器,请检查你的互联网连接')


# noinspection PyTypeChecker
def get_weather():
    api_wcs2 = wcs('api.seniverse.com', 3)
    if api_wcs2:
        data = find()
        if data == 'Error_ValueNone':
            tk.messagebox.showerror('错误', '未输入城市')
        elif not data == 'Error_ValueNone':
            try:
                data['status']
            except KeyError:
                # T
                # 访问数据
                # location_id = data['results'][0]['location']['id']
                city_name = data['results'][0]['location']['name']
                text_day = data['results'][0]['daily'][0]['text_day']
                text_night = data['results'][0]['daily'][0]['text_night']
                # code_day = data['results'][0]['daily'][0]['code_day']\
                # code_night = data['results'][0]['daily'][0]['code_night']
                today_date = data['results'][0]['daily'][0]['date']
                high_temp = data['results'][0]['daily'][0]['high']
                low_temp = data['results'][0]['daily'][0]['low']
                temp = str((int(high_temp) + int(low_temp)) / 2)
                rainfall = data['results'][0]['daily'][0]['rainfall']
                # precip = data['results'][0]['daily'][0]['precip']
                wind_direction = data['results'][0]['daily'][0]['wind_direction']
                wind_speed = data['results'][0]['daily'][0]['wind_speed']
                humidity = data['results'][0]['daily'][0]['humidity']
                last_update = data['results'][0]["last_update"]

                text.configure(state='normal')
                text.delete('1.0', 'end')
                text.insert('end', '城市: ' + city_name + '\n')
                text.insert('end',
                            '温度: ' + temp + '℃  ' + '最高温:' + high_temp + '℃  ' + '最低温:' + low_temp + '℃' + '\n')
                text.insert('end', '日期: ' + today_date + '\n')
                text.insert('end', '天气: ' + text_day + '-' + text_night + '\n')
                text.insert('end', '降水量: ' + rainfall + '\n')
                # text.insert('end', '降冰雹量: ' + precip + '\n')
                text.insert('end', '风向: ' + wind_direction + '\n')
                text.insert('end', '风速: ' + wind_speed + '\n')
                # text.insert('end', '风级: ' +  + '\n')
                text.insert('end', '湿度: ' + humidity)
                if update_value:
                    text.insert('end', '\n' + '       ' + last_update)
                elif not update_value:
                    pass
                text.configure(state='disabled')
            else:
                # F
                find_error(data)
    elif not api_wcs2:
        tk.messagebox.showerror('错误', '无法访问天气API服务器,请检查你的互联网连接')


update_value = False
title_name = '天气查询系统 Alpha-5.8.5'

window = tk.Tk()
window.title(title_name)
window.geometry('460x350')
window.geometry('+500+250')
window.resizable(False, False)

menubar = tk.Menu(window)  # 创建一个菜单栏
more_menu = tk.Menu(menubar, tearoff=False)
more_menu.add_command(label='设置', command=setting)
more_menu.add_command(label='帮助', command=forhelp)
more_menu.add_command(label='关于', command=about)

# more_menu.add_command(label='更新日志', command=a)
more_menu.add_separator()  # 添加一条分隔线
more_menu.add_command(label='退出', command=sys.exit)
menubar.add_cascade(label='更多', menu=more_menu)
# 显示菜单
window.config(menu=menubar)

# 天气查询框子
labelframe = tk.LabelFrame(width=430, height=238, text="天气查询", font=('', 11))
labelframe.grid(column=0, row=0, padx=15, pady=10)
# '城市:'字符
tk.Label(window, text='城市:', font=('', 14)).place(x=50, y=35)
# 输入框
entry = tk.Entry(window, font=('', 14))
entry.place(x=140, y=37)
# 按钮
tk.Button(window, text=' 查询 ', relief=tk.GROOVE, font=('', 15), command=get_weather).place(x=50, y=280)
tk.Button(window, text=' 未来两天 ', relief=tk.GROOVE, font=('', 15), command=get_weather_two).place(x=170, y=280)
tk.Button(window, text=' 退出 ', relief=tk.GROOVE, font=('', 15), command=sys.exit).place(x=330, y=280)
# 显示框
text = tk.Text(window, font=('', 14))
text.configure(state='disabled')
text.place(x=33, y=70, width=392, height=157)

baidu_wcs = wcs('www.baidu.com', 3)
api_wcs = wcs('api.seniverse.com', 3)

if baidu_wcs:
    if api_wcs:
        pass
    elif not api_wcs:
        tk.messagebox.showerror('错误', '无法访问天气API服务器,请检查你的互联网连接')
        sys.exit()
elif not baidu_wcs:
    tk.messagebox.showerror('错误', '无法连接互联网')
    sys.exit()

# window循环
window.mainloop()
